<?php

/* Web Statistics and Analytics Console (PHP)
 *  chart.php
 *  Author: Trevor Bidyk
 *  Created: January 1, 2000
 *  Last modified: April 5, 2011
 *   (C) Us 2011
 *   Uses Simple PHP Framework, licensed under the FreeBSD license.
 *    View license in ./include/LICENSE.
 *   All rights reserved.
 */
require_once('./includes/master.inc.php');
require_once('./functions.statistics.php');
if (!$Auth->loggedIn()) {
    require_once('./subpages/chart/error.php');
    exit;
}
// Display an awesome error if any parameter is not set.
if (!isset($_GET['ViewEvent']) || !isset($_GET['ViewTimeMode']) || !isset($_GET['ViewDay']) || !isset($_GET['ViewMonth']) || !isset($_GET['ViewYear'])) {
    header('Content-type: image/png');
    include('./subpages/chart/parameters.png');
    exit;
}
$db = Database::getDatabase();

// Fetch the available events.
$EventIDs = $EventNames = $Temp = array();
$Query = 'SELECT Type_ID, Type_Name FROM Event_Type';
$Result = $db->query($Query);
if ($db->hasRows($Result)) {
//    var_dump($db->GetRows($Result));
    $EventCount = $db->numRows($Result);
    for ($i = 0; $i < $EventCount; $i++) {
        $Temp = $db->getRow();
        $EventIDs[] = $Temp['Type_ID'];
        $EventNames[] = $Temp['Type_Name'];
    }
} else {
    require_once('./subpages/chart/error.php');
    exit;
}

$ViewEvent = SanitizeWhiteList($_GET['ViewEvent'], $EventIDs, $EventIDs[0]);
$ViewTimeMode = SanitizeWhiteList($_GET['ViewTimeMode'], array('week', 'month', 'year'), 'week');

$ViewDay = SanitizeWhiteList($_GET['ViewDay'], range(1, 31), date('j'));
$ViewMonth = SanitizeWhiteList($_GET['ViewMonth'], range(1, 12), date('n'));
$ViewYear = SanitizeWhiteList($_GET['ViewYear'], range(2010, 2012), date('Y'));

$MonthArray = array();
for ($i = 1; $i < 13; $i++) {
    $MonthArray[] = date("F", mktime(0, 0, 0, $i, 1));
}


if ($ViewTimeMode == 'week') {
        $StartingDate = FormatDate($ViewDay, $ViewMonth, $ViewYear);
        // I hope that PHP is smart enough to just switch the month over in the case of an overflow.
        $EndingDate = FormatDate(($ViewDay + 7), $ViewMonth, $ViewYear);
        $Query = "SELECT EventType.Type_Name, COUNT(Event.Event_ID) AS EventCount, CONVERT(Date_Event, DATE) AS EventDate FROM The_Event AS Event LEFT JOIN Event_Type AS EventType ON EventType.Type_ID = Event.Type_ID WHERE Event.Type_ID = $ViewEvent AND Event.Date_Event BETWEEN '$StartingDate'AND '$EndingDate' GROUP BY EventDate ORDER BY EventDate ASC";
    } else if ($ViewTimeMode == 'month') {
        $StartingDate = FormatDate(1, $ViewMonth, $ViewYear);
        // This will fetch the last day of the given month. (Hopefully correctly).
        $EndingDate = FormatDate(date('t', mktime(0, 0, 0, $ViewMonth, 1, $ViewYear)), $ViewMonth, $ViewYear);
    } else if ($ViewTimeMode == 'year') {
        $StartingDate = FormatDate(1, 1, $ViewYear);
        // This will fetch the last day of the given month. (Hopefully correctly).
        $EndingDate = FormatDate(31, 12, $ViewYear);
    }

    $Query = "SELECT EventType.Type_Name, COUNT(Event.Event_ID) AS EventCount, CONVERT(Date_Event, DATE) AS EventDate FROM The_Event AS Event LEFT JOIN Event_Type AS EventType ON EventType.Type_ID = Event.Type_ID WHERE Event.Type_ID = $ViewEvent AND Event.Date_Event BETWEEN '$StartingDate'AND '$EndingDate' GROUP BY EventDate ORDER BY EventDate ASC";
    $Result = $db->query($Query);
    if ($db->hasRows($Result)) {
        $Rows = $db->getRows($Result);
        $i = 1;
        $DataString = 't:';
        $LargestValue = (int) $Rows[0]['EventCount'];
        foreach ($Rows as $Row) {
            // Find the largest value.
            if ((int) $Rows['EventCount'] < $LargestValue) {
                $LargestValue = (int) $Rows['EventCount'];
            }
            $DataString .= $Row['EventCount'] . ',';
        }
        $DataString = trim($DataString, ',');
        $XAxisLabel = trim($XAxisLabel, '|');
    }

$ChartParameters = array(
    'chtt' => $EventNames[($ViewEvent - 1)]. " events ($ViewTimeMode of " . $MonthArray[($ViewMonth -1)] . " $ViewDay, $ViewYear)",
    'cht' => 'lc',               // Chart type (always line chart).
    'chs' => '600x300',         // Chart size (400 x 500).
    'chls' => '2',

    'chxt' => 'x,y',            // Visible axis (x and y).
    'chxr' => '1,0,31|1,0,10',  // X axis range.
    'chm' => 'B,ACC357BB,0,0,0',
    'chco' => '515554',
    'chm' => 'B,C5D4B5BB,0,0,0|o,515554,0,-1,8',

    'chd' => $DataString,
    'chds' => '0,11',
);

$Result = post_request("http://chart.apis.google.com/chart", $ChartParameters);

if ($Result['status'] == 'ok') {
    $Headers = explode("\n", $Result['header']);
    foreach ($Headers as $H) {
        header($H);
    }
    echo $Result['content'];
    exit;
} else {
    require_once('./subpages/chart/post.php');
    exit;
}

// This function creates a nice post request.
// We access Google's Chart API using a post request.
// Borrowed from http://www.jonasjohn.de/snippets/php/post-request.htm
// I intend to return it one day.
function post_request($url, $data, $referer='') {

    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);

    // parse the given URL
    $url = parse_url($url);

    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }

    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];

    // open a socket connection on port 80 - timeout: 30 sec
    $fp = fsockopen($host, 80, $errno, $errstr, 30);

    if ($fp) {

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");

        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");

        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: " . strlen($data) . "\r\n");            // I don't trust this.
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = '';
        while (!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }
    } else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }

    // close the socket connection:
    fclose($fp);

    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);

    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';

    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content
    );
}

?>
